package com.jmda.platform.repository.mybatis.service;

import com.jmda.platform.commom.SpringContextUtil;
import com.jmda.platform.commom.util.FileUtil;
import com.jmda.platform.repository.ResositoryException;
import com.jmda.platform.repository.mybatis.scan.MybatisXmlMapperScan;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.util.HashMap;
import java.util.Map;

@Service
public class MybatisXmlMappersService {

	public void remove(String basePath, String id) throws ResositoryException {
		// TODO Auto-generated method stub
		FileUtil.removeFile(basePath + id + ".dao");
	}

	@Autowired(required=false)
	@Qualifier("freemarkerConfig")
	FreeMarkerConfig freemarkerConfig;
	public void storeWorkList(String basePath, String id, String sql) throws ResositoryException {
		// TODO Auto-generated method stub
		Map<String, String> tmpMap = new HashMap<String, String>();
		tmpMap.put("id", id);
		tmpMap.put("sql", sql);
		tmpMap.put("orderBy", "order by ${sort} ${order}");
		Template template;
		try {
			template = freemarkerConfig.getConfiguration().getTemplate("system/sys_worklist_dao.ftl");
			String fileContent = FreeMarkerTemplateUtils.processTemplateIntoString(template, tmpMap);
			FileUtil.write(basePath + id + "_dao.xml", fileContent);
			SpringContextUtil.getBean(MybatisXmlMapperScan.class).reloadMybatisMapper();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void storeForm(String basePath, Map<String,Object> map) throws ResositoryException {
		Template template;
		try {
			template = freemarkerConfig.getConfiguration().getTemplate("system/sys_form_dao.ftl");
			String fileContent = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
			FileUtil.write(basePath + map.get("id") + "_dao.xml", fileContent);
			SpringContextUtil.getBean(MybatisXmlMapperScan.class).reloadMybatisMapper();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
